import type { Review, QueryReviewsParams, ReviewsResponse, RatingStats } from '~/types'

export const useReviews = () => {
  const { $api } = useNuxtApp()

  // 获取评论列表
  const getReviews = async (params: QueryReviewsParams): Promise<ReviewsResponse> => {
    const response = await $api('/reviews', {
      params,
    })
    return response as ReviewsResponse
  }

  // 获取单个评论
  const getReview = async (id: number): Promise<Review> => {
    const response = await $api(`/reviews/${id}`)
    return response as Review
  }

  // 创建评论
  const createReview = async (data: Partial<Review>): Promise<Review> => {
    const response = await $api('/reviews', {
      method: 'POST',
      body: data,
    })
    return response as Review
  }

  // 更新评论
  const updateReview = async (id: number, data: Partial<Review>): Promise<Review> => {
    const response = await $api(`/reviews/${id}`, {
      method: 'PATCH',
      body: data,
    })
    return response as Review
  }

  // 删除评论
  const deleteReview = async (id: number): Promise<void> => {
    await $api(`/reviews/${id}`, {
      method: 'DELETE',
    })
  }

  // 标记评论为有帮助/无帮助
  const markReviewHelpful = async (id: number, helpful: boolean): Promise<Review> => {
    const response = await $api(`/reviews/${id}/helpful`, {
      method: 'POST',
      body: { helpful },
    })
    return response as Review
  }

  // 获取工具的评分统计
  const getToolRatingStats = async (toolId: number): Promise<RatingStats> => {
    const response = await $api(`/reviews/tool/${toolId}/stats`)
    return response as RatingStats
  }

  // 检查用户是否已评论
  const checkUserReviewed = async (toolId: number): Promise<boolean> => {
    const response = await $api(`/reviews/tool/${toolId}/check`) as { hasReviewed: boolean }
    return response.hasReviewed
  }

  return {
    getReviews,
    getReview,
    createReview,
    updateReview,
    deleteReview,
    markReviewHelpful,
    getToolRatingStats,
    checkUserReviewed,
  }
}

